package com.sita.bike.services;

import android.app.IntentService;
import android.content.Intent;
import android.util.Log;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.sita.bike.support.GlobalContext;

/**
 * IntentService的实现类：每隔5s save gps
 * mark man
 */
public class GPSLoggerService extends IntentService {
    private static final String TAG = GPSLoggerService.class.getSimpleName();

    // 发送的广播对应的action
    private static final String COUNT_ACTION = "com.sita.bike.COUNT_ACTION";
    private static final String GPS_ACTION = "com.sita.bike.GPS_ACTION";

    // 线程：用来实现每隔200ms发送广播
    private static GPSLoggerThread mGPSLoggerThread = null;
    // 数字的索引
    private static int index = 0;

    public GPSLoggerService() {
        super("IntentServiceSub");
        Log.d(TAG, "create IntentServiceSub");
    }

    @Override
    public void onCreate() {
        Log.d(TAG, "onCreate");
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        Log.d(TAG, "onDestroy");
        super.onDestroy();
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.d(TAG, "onHandleIntent");
        // 非首次运行IntentServiceSub服务时，执行下面操作
        // 目的是将index设为0
        if (mGPSLoggerThread != null) {
            index = 0;
            return;
        }

        // 首次运行IntentServiceSub时，创建并启动线程
        mGPSLoggerThread = new GPSLoggerThread();
        mGPSLoggerThread.start();
    }

    private class GPSLoggerThread extends Thread {
        AMapLocationClient locationClient = GlobalContext.getLocationClient();
        AMapLocation loc;
        long utc;

        public GPSLoggerThread() {
            locationClient.startLocation();
        }

        private void getLocation() {
            loc = locationClient.getLastKnownLocation();
            utc = loc.getTime();
        }

        @Override
        public void run() {
            index = 0;
            try {
                while (true) {
                    getLocation();
                    // 将数字+2,
                    index += 2;

                    // 将index通过广播发送出去
                    Intent intent = new Intent(GPS_ACTION);
                    intent.putExtra("utc", utc);
                    intent.putExtra("lat", loc.getLatitude());
                    intent.putExtra("lon", loc.getLongitude());
                    sendBroadcast(intent);
                    Log.d(TAG, "GpsLoggerThread index:" + index);

//					// 若数字>=100 则退出
//					if (index >= 100) {
//						if ( mGPSLoggerThread != null)
//							mGPSLoggerThread = null;
//
//						return ;
//					}

                    //
                    this.sleep(5000);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}